package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"time"
)

type dept struct {
	Id   int    `db:"id"`
	Name string `db:"name"`
}

type stuCount struct {
	Result   string `db:"result"`
	StuCount int    `db:"stu_count"`
}

type st struct {
	Id   int    `db:"id"`
	Name string `db:"name"`
	No   string `db:"no"`
}

func main() {
	db := InitMySQLDB(mysqlConfig{
		Host:     "localhost",
		Port:     31000,
		UserName: "root",
		Password: "Test123dev",
		DbName:   "itheima",
	})
	//var d []dept
	//var d []stuCount
	//var sc int64 = 10
	var d st
	//result := db.Raw("call p1();").Scan(&d)
	//result := db.Raw("call p5(?);", sc).Scan(&d)
	result := db.Raw("call p6(?);", 3).Scan(&d)
	fmt.Println(result.RowsAffected, "==========")
	fmt.Println(result.Error, "----------")
	fmt.Printf("%#v ccccccccc\n", d)
}

type mysqlConfig struct {
	Host     string `mapstructure:"host" yaml:"host" json:"host"`
	Port     int    `mapstructure:"port" yaml:"port" json:"port"`
	UserName string `mapstructure:"userName" yaml:"userName" json:"userName"`
	Password string `mapstructure:"password" yaml:"password" json:"password"`
	DbName   string `mapstructure:"dbName" yaml:"dbName" json:"dbName"`
}

func InitMySQLDB(mysqlConfig mysqlConfig) *gorm.DB {
	var (
		userName = mysqlConfig.UserName
		password = mysqlConfig.Password
		host     = mysqlConfig.Host
		port     = mysqlConfig.Port
		dbName   = mysqlConfig.DbName
	)
	dbHost := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v", userName, password, host, port, dbName)
	dsn := dbHost + "?charset=utf8mb4&parseTime=True&loc=Local&timeout=10s"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 表名自动添加复数 -> 设置为禁止
		},
		Logger: logger.New(
			log.New(log.Writer(), "\r\n", log.LstdFlags), // io writer
			logger.Config{
				SlowThreshold:             time.Second, // 慢 SQL 阈值
				LogLevel:                  logger.Info, // 日志级别
				IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
				Colorful:                  true,        // 启用彩色打印
			},
		),
	})

	if err != nil {
		panic(err)
	}
	// maxIdleConns < maxOpenConns
	sqlDB, err := db.DB()

	if err != nil {
		panic(err)
	}

	// SetMaxIdleConns 设置空闲连接池中的最大连接数。
	sqlDB.SetMaxIdleConns(50)

	// SetMaxOpenConns 设置与数据库的最大打开连接数。
	sqlDB.SetMaxOpenConns(1000)

	// SetConnMaxLifetime 设置可以重用连接的最长时间。
	sqlDB.SetConnMaxLifetime(time.Hour)

	return db
}
